﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.Mvc;
using DistributeTransaction.DAL;
using DistributeTransaction.Models;
using DistributeTransaction.Utils;

namespace DistributeTransaction.Controllers
{
    public abstract class BaseController : Controller
    {
        public const int PageSize = 20;
        protected DatabaseContext DBContext = new DatabaseContext();

        public BaseController()
            :base()
        {
        }

        protected override void Dispose(bool disposing)
        {
            DBContext.Dispose();
            base.Dispose(disposing);  
        }

        protected Guid CustomerId
        {
            get
            {
                if (User.Identity.IsAuthenticated)
                {
                    object value = Session[User.Identity.Name];
                    if (value == null)
                    {
                        CustomerRepository ur = new CustomerRepository(DBContext);
                        value = ur.GetByLoginName(User.Identity.Name);
                        Session[User.Identity.Name] = value;
                    }
                    if (value != null && value is Customer)
                    {
                        return ((Customer)value).UserId;
                    }
                }
                return Guid.Empty;
            }
        }

        protected IEnumerable<int> ParseProductIds(string input)
        {
            if (!string.IsNullOrEmpty(input))
            {
                return input.Split(',')
                        .Where(s => StringUtils.IsNumber(s))
                        .Select(s => int.Parse(s));
            }
            return new List<int>();
        }

        protected IEnumerable<int> ParseProductIds(FormCollection formCollection)
        {
            if (!string.IsNullOrEmpty(formCollection["selectedRows"]))
            {
                return ParseProductIds(formCollection["selectedRows"]);
            }
            return new List<int>();
        }

    }
}
